﻿using Framework.FreeSqlClient.Attribute;
using Framework.FreeSqlClient.InteFace;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace Framework.FreeSqlClient
{
    /// <summary>
    /// 自动注入FreeSql
    /// </summary>
    public static class AddFreeSqlFunc
    {
        /// <summary>
        /// 自动注入FreeSql
        /// </summary>
        /// <param name="service"></param>
        /// <param name="configuration"></param>
        public static void AddFreeSql(this IServiceCollection service, IConfiguration configuration = null)
        {
            var freeSqls = Assembly.GetExecutingAssembly().GetTypes().Where(x => x.IsInterface && x.GetInterfaces().Contains(typeof(IFreeSqlFactory))).ToList();
            var freeSqlAchieve = Assembly.GetExecutingAssembly().GetTypes().Where(x => x.IsClass && x.GetInterfaces().Contains(typeof(IFreeSqlFactory))).ToList();

            foreach (var item in freeSqls)
            {
                try
                {
                    var attr = item.GetCustomAttribute<InjectionFreeSqlAttribute>();
                    if (attr == null) continue;
                    string connection = configuration?.GetSection("DBConfig")?[attr.DBConnection] ?? attr.DBConnection;
                    var achieve = freeSqlAchieve.FirstOrDefault(x => item.IsAssignableFrom(x));
                    if (achieve == null) continue;
                    var ferr = new FreeSql.FreeSqlBuilder()
                        .UseConnectionString(attr.DataType, connection)
                        .UseAutoSyncStructure(true)
                        .Build();
                    service.AddSingleton(item, sp =>
                    {
                        return Activator.CreateInstance(achieve, ferr);
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{item.Name}-FreeSql自动注入失败，失败原因：{ex.Message}");
                }
            }
        }
    }
}
